﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.ComponentModel;
using System.Diagnostics;

 namespace Share
{
    public class VMComboBox : ComboBox
    {
        public VMComboBox()
        {
            this.Loaded += new System.Windows.RoutedEventHandler(VMComboBox_Loaded);
            if (Style == null)
                Style = new Style(typeof(ComboBox), (Style)Application.Current.Resources[typeof(ComboBox)]);
            SetupRevertToDefault();
            
        }
        public bool IsShowItemAll { get; set; }
        public bool InDesignMode()
        { 
            if(Debugger.IsAttached)
                return DesignerProperties.GetIsInDesignMode(this);
            return false;
        }
        public bool CanLoadData()
        {
            return !InDesignMode();
        }
        void VMComboBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            this.GotFocus -= new RoutedEventHandler(VMComboBox_GotFocus);
            this.GotFocus += new RoutedEventHandler(VMComboBox_GotFocus);
            //this.TextInput -= new System.Windows.Input.TextCompositionEventHandler(VMComboBox_TextInput);
            //this.TextInput += new System.Windows.Input.TextCompositionEventHandler(VMComboBox_TextInput);
        }

       public string VMComboBox_CheckValidParamater()
        {
            if (!string.IsNullOrEmpty(this.Text) && this.SelectedValue == null)
            {

                return "Giá trị này không có";
                
                
            }
            return string.Empty;
        }
        #region SetupRevertToDefault
        bool SetupRevertToDefault_IsKeyDown = false;
        /// <summary>
        /// Muc dich la khi xoa du lieu Combobox -> can gan gia tri 0 hay NULL vao datacontext
        /// Chi lam khi ma user thuc su tac dong: chuot hay ban phim
        /// </summary>
        void SetupRevertToDefault()
        {
            this.PreviewKeyDown -= new System.Windows.Input.KeyEventHandler(SetupRevertToDefault_VMComboBox_PreviewKeyDown);
            this.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(SetupRevertToDefault_VMComboBox_PreviewKeyDown);
            this.SelectionChanged -= new SelectionChangedEventHandler(VMComboBox_SelectionChanged);
            this.SelectionChanged += new SelectionChangedEventHandler(VMComboBox_SelectionChanged);
            this.DataContextChanged -= new DependencyPropertyChangedEventHandler(SetupRevertToDefault_VMComboBox_DataContextChanged);
            this.DataContextChanged += new DependencyPropertyChangedEventHandler(SetupRevertToDefault_VMComboBox_DataContextChanged);
        }

        void SetupRevertToDefault_VMComboBox_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            SetupRevertToDefault_IsKeyDown = false;
        }

        void VMComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SetupRevertToDefault_Run();
        }
        void SetupRevertToDefault_Run()
        {
            if (SetupRevertToDefault_IsKeyDown == true)
            {
                if (this.SelectedItem == null)
                {
                    string sPath = this.SelectedValuePath;
                    if (this.DataContext != null)
                    {
                        var propDataContext = this.DataContext.GetType().GetProperty(sPath);
                        if (propDataContext != null && propDataContext.CanWrite && propDataContext.CanRead)
                        {
                            var oldValue = propDataContext.GetValue(this.DataContext, null);
                            var defaultValue = Activator.CreateInstance(propDataContext.PropertyType, null);
                            if (defaultValue != oldValue)
                            {
                                propDataContext.SetValue(this.DataContext, defaultValue, null);
                            }
                        }
                    }
                }
            }
        }
        void SetupRevertToDefault_VMComboBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            SetupRevertToDefault_IsKeyDown = true;
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                SetupRevertToDefault_Run();
            }
        }
        #endregion
        void VMComboBox_GotFocus(object sender, RoutedEventArgs e)
        {

        }
        #region IsRequired
        public static readonly DependencyProperty IsRequiredProperty =
             DependencyProperty.Register("IsRequired", typeof(bool),
             typeof(VMComboBox), new FrameworkPropertyMetadata(false, OnCurrentTimePropertyChanged));
        private static void OnCurrentTimePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
        {
            VMComboBox vmt = source as VMComboBox;
            if (vmt != null)
            {
                if (e.NewValue == (object)true)
                {
                    vmt.Style.Triggers.Add(CreateTrigger4IsRequired());
                }
            }
        }

        public bool IsRequired
        {
            get { return (bool)GetValue(IsRequiredProperty); }
            set { SetValue(IsRequiredProperty, value); }
        }
        private Style CreateStyle()
        {
            Style stypeofCombobox = (Style)Application.Current.Resources[typeof(ComboBox)];
            Style _style = new Style(typeof(VMComboBox), stypeofCombobox);
            _style.Triggers.Add(CreateTrigger4IsRequired());
            return _style;
        }

        public bool IsValid
        {
            get
            {
                if ((this.Text.Trim().Length == 0 || this.SelectedIndex == -1) && IsRequired)
                    return false;
                return true;
            }
        }

        public static MultiDataTrigger CreateTrigger4IsRequired()
        {
            MultiDataTrigger _datatrigger = new MultiDataTrigger();
            Condition con1 = new Condition() { Binding = new Binding("SelectedIndex") { RelativeSource = new RelativeSource(RelativeSourceMode.Self) }, Value = -1 };
            Condition con2 = new Condition() { Binding = new Binding("IsRequired") { RelativeSource = new RelativeSource(RelativeSourceMode.Self) }, Value = true };
            _datatrigger.Conditions.Add(con1);
            _datatrigger.Conditions.Add(con2);
            Setter st1 = new Setter(ComboBox.BorderBrushProperty, Brushes.Red);
            Setter st2 = new Setter(ComboBox.ToolTipProperty, "Không được nhập dữ liệu trống");
            _datatrigger.Setters.Add(st1);
            _datatrigger.Setters.Add(st2);
            return _datatrigger;
        }

        #endregion

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.Style = CreateStyle();
        }
        /// <summary>
        /// Support value type
        /// </summary>
        public void DisplayZeroOrNull()
        {
            string sPath = this.SelectedValuePath;
            if (this.DataContext != null)
            {
                var propDataContext = this.DataContext.GetType().GetProperty(sPath);
                if (propDataContext != null && propDataContext.CanWrite && propDataContext.PropertyType.IsValueType)
                {
                    object firstValue = Activator.CreateInstance(propDataContext.PropertyType) ;
                    propDataContext.SetValue(this.DataContext, firstValue, null);
                }
            }
        }
        public void DisplayFirstItem()
        {
            if (this.Items.Count > 0)
            {
                string sPath = this.SelectedValuePath;
                var firstItem = this.Items[0];
                if (firstItem != null && this.DataContext != null)
                {
                    var prop = firstItem.GetType().GetProperty(sPath);
                    var propDataContext = this.DataContext.GetType().GetProperty(sPath);
                    if (prop != null && propDataContext != null && prop.CanRead && propDataContext.CanWrite)
                    {
                        object firstValue = prop.GetValue(firstItem, null);
                        propDataContext.SetValue(this.DataContext, firstValue, null);
                    }
                }
            }
        }

    }
}
